import java.util.ArrayList;
import java.util.List;

public class Solution {
    List<List<Integer>> ret;
    List<Integer> path;
    int aim;

    public List<List<Integer>> combinationSum(int[] nums, int target) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        aim = target;

        dfs(nums, 0, 0);
        return ret;
    }

    private void dfs(int[] nums, int pos, int sum) {
        if(aim == sum){
            ret.add(new ArrayList<>(path));
            return;
        }
        if(aim < sum || pos >= nums.length){
            return;
        }
        for (int i = pos; i < nums.length; i++) {
            path.add(nums[i]);
            sum += nums[i];
            dfs(nums, i+1, sum);
            sum -= nums[i];
            path.remove(path.size() - 1);
        }
    }
}
